package com.simple.mqtt.server.serializer;

import com.simple.mqtt.common.tool.JsonTool;
import com.simple.mqtt.common.tool.LogTool;

import java.nio.charset.StandardCharsets;

/**
 * JSON 消息序列化器
 *

 */
public class JsonMessageSerializer implements IMessageSerializer {
    @Override
    public byte[] serialize(Object obj) {
        try {
            if (obj == null) {
                return new byte[0];
            }
            if (obj instanceof byte[]) {
                return (byte[]) obj;
            }
            if (obj instanceof String) {
                return ((String) obj).getBytes(StandardCharsets.UTF_8);
            }
            String json = JsonTool.toJsonStr(obj);
            if (json == null) {
                return new byte[0];
            }
            return json.getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            LogTool.error("Error serializing message", e);
            return new byte[0];
        }
    }
}

